package com.x.scratch.service;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.x.scratch.model.WxPayRequest;
import com.x.scratch.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class WxService {
    private Logger logger = LoggerFactory.getLogger(WxService.class);

    private WXPay wxPay;

    public WxService() {

    }

    public void setWxPay(WXPay wxPay) {
        this.wxPay = wxPay;
    }

    /**
     * 微信下單接口
     */
    public WxPayRequest doUnifiedOrder(String body, String outTradeNo, Double money, String openid) {
        try {
            String totalFee = String.valueOf(money * 100);
            totalFee = totalFee.substring(0, totalFee.lastIndexOf("."));
            logger.info("totalFee = " + totalFee);

            Map<String, String> payData = new HashMap<String, String>();
            String nonceStr = WXPayUtil.generateNonceStr();
            String timeStamp = Long.toString(System.currentTimeMillis());
            payData.put("appid", Constant.WX_APP_ID);
            payData.put("mch_id", Constant.WX_MCHID);//商户平台id
            payData.put("nonce_str", nonceStr);
            payData.put("body", "嗨皮猫" + body);
            payData.put("device_info", "");
            payData.put("out_trade_no", outTradeNo);
            payData.put("fee_type", "CNY");
            payData.put("total_fee", totalFee);
            payData.put("spbill_create_ip", "192.168.1.1");
            payData.put("notify_url", "http://www.iwooch.com.cn/controller/wx/pay/notify");
            payData.put("trade_type", "JSAPI");
            payData.put("openid", openid);
            for (Map.Entry entry : payData.entrySet()) {
                logger.info("payData = " + entry.getKey() + ", Value = " + entry.getValue());
            }
//            payData.put("timeStamp", timeStamp);
            // data.put("time_expire", "20170112104120");

            Map<String, String> payMap = wxPay.unifiedOrder(payData);
            String prepayId = payMap.get("prepay_id");
            String packageStr = "prepay_id=" + prepayId;
            for (Map.Entry entry : payMap.entrySet()) {
                logger.info("payMap = " + entry.getKey() + ", Value = " + entry.getValue());
            }


            Map<String, String> signData = new HashMap<String, String>();
            signData.put("appId", Constant.WX_APP_ID);//公众号id
            signData.put("timeStamp", timeStamp);
            signData.put("nonceStr", nonceStr);//随机字符串
            signData.put("package", packageStr);//注意prepay_id的值是一个键值对
            signData.put("signType", WXPayConstants.MD5);
            String paySign = WXPayUtil.generateSignature(signData, Constant.WX_KEY);
            logger.info("paySign  = " + paySign);

            WxPayRequest wxPayRequest = new WxPayRequest();
            wxPayRequest.setAppId(Constant.WX_APP_ID);
            wxPayRequest.setOpenId(openid);
            wxPayRequest.setTimeStamp(timeStamp);
            wxPayRequest.setNonceStr(nonceStr);
            wxPayRequest.setPackageStr(packageStr);
            wxPayRequest.setSignType(WXPayConstants.MD5);
            wxPayRequest.setPaySign(paySign);
//            Map<String, String> payData = new HashMap<String, String>();
//            payData.put("appid", Constant.WX_APP_ID);//公众号id
//            payData.put("body", body);//商品描述
//            payData.put("mch_id", Constant.WX_MCHID);//商户平台id
//            payData.put("nonce_str", nonceStr);//随机字符串
//            payData.put("notify_url", Constant.WX_NOTIFY_URL);//异步回调api
//            payData.put("openid", openid);
//            payData.put("out_trade_no", outTradeNo);//商品订单号
//            payData.put("spbill_create_ip", "192.168.1.1");//支付ip
//            payData.put("total_fee", totalFee);//真实金额
//            payData.put("trade_type", "JSAPI");//JSAPI、h5调用
//            payData.put("sign", sign);
//            Map<String, String> payMap = wxPay.unifiedOrder(payData);
//            for (Map.Entry entry : payMap.entrySet()) {
//                logger.info("doUnifiedOrder   Key = " + entry.getKey() + ", Value = " + entry.getValue());
//            }
//            HttpClient.httpRequest()
            return wxPayRequest;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            return null;
        }
    }

//    /**
//     * 退款 已测试
//     */
//    public void doRefund(String out_trade_no, String total_fee) {
//        logger.info("退款时的订单号为：" + out_trade_no + "退款时的金额为:" + total_fee);
//        String amt = String.valueOf(Double.parseDouble(total_fee) * 100);
//        logger.info("修正后的金额为：" + amt);
//        logger.info("最终的金额为：" + amt.substring(0, amt.lastIndexOf(".")));
//        HashMap<String, String> data = new HashMap<String, String>();
//        data.put("out_trade_no", out_trade_no);
//        data.put("out_refund_no", out_trade_no);
//        data.put("total_fee", amt.substring(0, amt.lastIndexOf(".")));
//        data.put("refund_fee", amt.substring(0, amt.lastIndexOf(".")));
//        data.put("refund_fee_type", "CNY");
//        data.put("op_user_id", scratchWxPayConfig.getMchID());
//
//        try {
//            Map<String, String> r = wxPay.refund(data);
//            logger.info("退款操作返回的参数为" + r);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
//
//
//    /**
//     * 微信验签接口
//     *
//     * @return
//     * @throws DocumentException
//     */
//    public boolean checkSign(String strXML) throws DocumentException {
//        SortedMap<String, String> smap = new TreeMap<String, String>();
//        Document doc = DocumentHelper.parseText(strXML);
//        Element root = doc.getRootElement();
//        for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
//            Element e = (Element) iterator.next();
//            smap.put(e.getName(), e.getText());
//        }
//        return isWechatSign(smap, scratchWxPayConfig.getKey());
//    }
//
//
//    private boolean isWechatSign(SortedMap<String, String> smap, String apiKey) {
//        try {
//            StringBuffer sb = new StringBuffer();
//            if (smap != null) {
//                for (Map.Entry<String, String> entry : smap.entrySet()) {
//                    String key = entry.getKey();
//                    String value = entry.getValue();
//                    if (!"sign".equals(key) && !"key".equals(key) && !StringUtils.isEmpty(value)) {
//                        sb.append(entry.getKey() + "=" + entry.getValue() + "&");
//                    }
//                }
//            }
//
//            sb.append("key=" + apiKey);
//            /** 验证的签名 */
//            String sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
//            /** 微信端返回的合法签名 */
//            String validSign = ((String) smap.get("sign")).toUpperCase();
//            return validSign.equals(sign);
//        } catch (Exception e) {
//            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
//        }
//    }

}
